package com.mornd.gulimall.product.controller;

import com.mornd.gulimall.common.core.result.AjaxResult;
import com.mornd.gulimall.common.core.validation.UpdateGroup;
import com.mornd.gulimall.product.entity.Category;
import com.mornd.gulimall.product.service.ICategoryService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 商品三级分类 前端控制器
 * </p>
 *
 * @author mornd
 * @since 2023-07-23
 */
@RestController
@RequestMapping("/product/category")
public class CategoryController {
    @Resource
    private ICategoryService categoryService;

    /**
     * 商品分类，树形结构
     *
     * @return
     */
    @GetMapping("/tree")
    public AjaxResult tree() {
        return AjaxResult.success(categoryService.tree());
    }

    @GetMapping("/{id}")
    public AjaxResult getById(@PathVariable Long id) {
        return AjaxResult.success(categoryService.getCacheById(id).orElse(null));
    }

    @PutMapping
    public AjaxResult save(@RequestBody @Validated Category category) {
        categoryService.save(category);
        return AjaxResult.success();
    }

    @PostMapping
    public AjaxResult update(@RequestBody @Validated(UpdateGroup.class) Category category) {
        categoryService.updateCascade(category);
        return AjaxResult.success();
    }

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable Long id) {
        // 检查
        if (!categoryService.isLeaf(id)) {
            return AjaxResult.error("该节点存在子节点，不可删除");
        } else {
            categoryService.delete(id);
            return AjaxResult.success();
        }
    }

    @PostMapping("/batchDelete")
    public AjaxResult batchDelete(@RequestBody List<Long> ids) {
        categoryService.batchDelete(ids);
        return AjaxResult.success();
    }
}
